package com.chanjiedata.changbs.module.main;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.adapter.MyBusinessAdapter;
import com.chanjiedata.changbs.adapter.MyPartnerAdapter;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.MemberOuterClass;
import com.chanjiedata.changbs.proto.Mystock;
import com.google.protobuf.InvalidProtocolBufferException;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by AndroidIntexh1 on 2018/6/4.
 */

public class PartnerTypeFragment extends BaseFragment {

    @BindView(R.id.fragment_recycleView)
    RecyclerView mRecycleView;
    Unbinder unbinder;

    private int page = 1; // 当前页数
    private int position;  // 当前viewPage的位置
    private int pagesize = 10;  // 当前viewPage的位置


    private List<Mystock.listOfMyBusiness.List> myBusinessBeans = new ArrayList<>();
    private MyBusinessAdapter mbAdapter; //


    private List<MemberOuterClass.my_partners_list.List> myPartnerBeans = new ArrayList<>(); // 系统消息
    private MyPartnerAdapter mpAdapter; // 系统消息适配器
    private String searchKey = "";

    public static PartnerTypeFragment NewInstance(int instanceType) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", instanceType);
        PartnerTypeFragment fragment = new PartnerTypeFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    /**
     * 获取布局文件
     *
     * @return
     */
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recycleview;
    }


    /**
     * 初始化操作步骤
     */
    @Override
    protected void init() {
        unbinder = ButterKnife.bind(this, rootView);
        position = getArguments().getInt("position");
    }

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        initRecycle();
        loadData();
    }

    /**
     * 加载数据
     */
    private void loadData() {
        if (position == 0) {
            Mystock.listOfMyBusiness.Builder builder = Mystock.listOfMyBusiness.newBuilder();
            builder.setVersion("2.0");
            builder.setSnCode(searchKey);
            NetworkManager.INSTANCE.post(Apis.listOfMyBusiness, builder.build().toByteArray(), page, new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    Mystock.listOfMyBusiness data =  Mystock.listOfMyBusiness.parseFrom(bytes);
                    List<Mystock.listOfMyBusiness.List> lists = data.getListList();
                    mbAdapter.addData(lists);
                    int size = lists.size();
                    if (size < 10) {
                        mbAdapter.loadMoreEnd(true);
                    } else {
                        mbAdapter.loadMoreComplete();
                    }
                    ((PartnerActivity) getActivity()).changeTabTitle(position, data.getTotalCount());
                }

                @Override
                public void onError(int errorCode, String errorMessage) {
                    showToast(errorMessage);
                }
            });

        } else if (position == 1) {
            MemberOuterClass.my_partners_list.Builder builder =  MemberOuterClass.my_partners_list.newBuilder();
            builder.setVersion("2.0");
            builder.setSearchKey(searchKey);
            NetworkManager.INSTANCE.post(Apis.my_partners_list, builder.build().toByteArray(),page,new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    MemberOuterClass.my_partners_list data =  MemberOuterClass.my_partners_list.parseFrom(bytes);
                    List<MemberOuterClass.my_partners_list.List> lists = data.getListList();
                    mpAdapter.addData(lists);
                    int size = lists.size();
                    if (size < 10) {
                        mpAdapter.loadMoreEnd(true);
                    } else {
                        mpAdapter.loadMoreComplete();
                    }
                    ((PartnerActivity) getActivity()).changeTabTitle(position, data.getTotalCount());
                }

                @Override
                public void onError(int errorCode, String errorMessage) {

                }
            });
        }
    }


    /**
     * 实例化线性底部RecyclerView
     * *
     */
    private void initRecycle() {
        mRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
        if (position == 0) {
            mRecycleView.setAdapter(mbAdapter = new MyBusinessAdapter(mContext, myBusinessBeans));
            mbAdapter.bindToRecyclerView(mRecycleView);
            mbAdapter.setEmptyView(R.layout.recycle_empty);
            // 每个item的点击事件
            mbAdapter.setOnItemClickListener((adapter, view, position) -> {
                Intent intent = new Intent(mContext, ShopShareProfitActivity.class);
                intent.putExtra("goods_id", myBusinessBeans.get(position).getInfo().getGoodsId());
                intent.putExtra("sn_code", myBusinessBeans.get(position).getInfo().getSnCode());
                intent.putExtra("title", "商户详情");
                startActivity(intent);
            });
            mbAdapter.setOnLoadMoreListener(() -> {
                page = mbAdapter.getData().size() / pagesize + 1;
                loadData();
            }, mRecycleView);
        } else if (position == 1) {
            mRecycleView.setAdapter(mpAdapter = new MyPartnerAdapter(mContext, myPartnerBeans));
            mpAdapter.bindToRecyclerView(mRecycleView);
            mpAdapter.setEmptyView(R.layout.recycle_empty);
            // 每个item的点击事件
            mpAdapter.setOnItemClickListener((adapter, view, position) -> {
                Intent intent = new Intent(mContext, PartnerMachineActivity.class);
                intent.putExtra("others_member_id", myPartnerBeans.get(position).getMemberId() + "");
                startActivity(intent);
            });
            mpAdapter.setOnLoadMoreListener(() -> {
                page = mpAdapter.getData().size() / pagesize + 1;
                loadData();
            }, mRecycleView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    public void searchData(String searchKey) {
        this.searchKey = searchKey;
        page = 1;
        if (position == 0) {
            myBusinessBeans.clear();
            mbAdapter.replaceData(myBusinessBeans);
        } else {
            myPartnerBeans.clear();
            mpAdapter.replaceData(myPartnerBeans);
        }
        loadData();
    }
}
